﻿﻿﻿function voipCall(){
	var oVoip = new Object;
	oVoip.userSession = "";
	oVoip.userName = "";
	oVoip.userPass = "";
	oVoip.extension = "";
	oVoip.exteId = 0;
	oVoip.userId = 0;
	oVoip.compId = 0;
	oVoip.ExteDialType=0;
	oVoip.exteLoginType=0;
	oVoip.lastWatertime = getNowTimes();
	oVoip.Waterline = 0;
	oVoip.CallBack_Call = function(kind,phone){};
	oVoip.CallBack_Answer = function(kind,phone){};
	oVoip.CallBack_HangUp = function(kind,phone,obj){};
	oVoip.CallBack_login = null;
	oVoip.CallBack_status = function(msg){};
	oVoip.CallBack_Key = function(keylist){};
	oVoip.CallUserInfo = function(oldUser,userInfo){};
	oVoip.Service_Call = function(phone){
		alert('呼叫电话：'+phone);
	};
	oVoip.ShowMsg = null;
	oVoip.status = -1;
	oVoip.kind = 1;
	oVoip.oldUser = null;
	oVoip.tcpWssPort = 0;
	oVoip.tcpWsPort = 0;
	oVoip.webTcpSocket = null;
	oVoip.lineId = GetRandomNum(100,21323322);
	oVoip.phone = null;
	//用户登录
	oVoip.init = function(url){
		oVoip.serviceUrl = url;
	};
	oVoip.TransferUser = function(phone,func){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"transferExten");  
		getJsonP(url,{descExten:phone},function(data) {
			func(data);		
		});
	};
	oVoip.setUserCheckInOut = function(aStatus,fun){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"setUserCheckInOut");  
		getJsonP(url,{status:aStatus},function(data) {
			fun(data);		
		});	
	};
	oVoip.CallPhone = function(phone,func){
		if(phone==null||phone.length<3){
			return;
		}
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"callbackPhone");  
//		url+='&paramvalue='+$('#paramvalue').val();
		getJsonP(url,{sourcePhone:oVoip.userName,descPhone:phone},function(data) {
			func(data);		
		});
	};
	oVoip.hangup = function(phone,func){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"hangupExten");  
		getJsonP(url,{phoneNum:phone},function(data) {
			func(data);		
		});
	}
	oVoip.userlogin = function(userName,userpass,oVoip){		
	    console.log(2)
		var url = oVoip.getUrl(userName,userpass,"getExtension");
		getJsonP(url,{},function(data) {
			if(data.code==0){
				oVoip.userSession = data.sessionId;
				oVoip.exteId = data.exteId;
				oVoip.compId = data.compId;
				oVoip.lineId = data.loginLine;
				oVoip.extension = data.extension.substr(0, 6);
				oVoip.userName = userName;
				oVoip.userId = data.extension;
				oVoip.userPass = userpass;
				oVoip.exteLoginType = data.exteLoginType;
				oVoip.ExteDialType = data.ExteDialType;
				oVoip.CallBack_login(0,"");
				oVoip.tcpWssPort = data.tcpWssPort;
				oVoip.tcpWsPort = data.tcpWsPort;
				oVoip.initSocket(data.host);
				oVoip.getLoadmonitor();
			}else{
				oVoip.userSesson = "";
				oVoip.exteId = 0;
				oVoip.compId = 0;
				oVoip.userName = "";
				oVoip.userPass = "";
				oVoip.CallBack_login(1,data.message);
			}
		});
	};
	oVoip.getLoadmonitor = function(){
		var url = oVoip.serviceUrl + 'voip/extensionmanager/loadmonitor.jsonp?callback=?&sessionId='+oVoip.userSession+"&extension="+oVoip.userName;
		getJsonP(url,{},function(data) {
			if(data.code==0&&data.rows!=null&&data.rows.length>0){
				oVoip.CallBack_status(data.rows[0]);
			}
			setTimeout(function(){oVoip.getLoadmonitor()},60000);
		});
	};
	oVoip.initSocket = function(host){
		if(window.location.protocol=='https:'){
			if(oVoip.tcpWssPort!=0){
				var wsUrl = "wss://"+host+":" +(oVoip.tcpWssPort);
				oVoip.webTcpSocket = new WebTcpSocket();						
				oVoip.webTcpSocket.initSocket(wsUrl,oVoip.userId,oVoip.doHandUpMsg);
			}else{
				oVoip.getLongWaterLine();
			}
		}else if(oVoip.tcpWsPort!=0){
			var wsUrl = "ws://"+host + ":" +(oVoip.tcpWsPort);
			oVoip.webTcpSocket = new WebTcpSocket();						
			oVoip.webTcpSocket.initSocket(wsUrl,oVoip.userId,oVoip.doHandUpMsg);
		}else{
			oVoip.getLongWaterLine();
		}
	};
	//取服务器是否发生变化
	oVoip.getLongWaterLine = function(){
		oVoip.lastWatertime = getNowTimes();
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"getLongWaterLine");
		getJsonP(url,{client:1,message:1,loginLine:oVoip.lineId},function(data) {
			if(data!=null&&data.code==0){
				if(data.waterline>oVoip.Waterline){
					if(oVoip.Waterline==0){
						oVoip.Waterline = data.waterline - 1;
					}
					if(data.msgs!=null){
						oVoip.HandleMsg(data.msgs);
					}					
				}
				if(data.userInfo!=null){
					oVoip.CallUserInfo(oVoip.oldUser,data.userInfo);
					oVoip.oldUser = data.userInfo;
				}
				if(data&&oVoip.CallBack_Key&&data.keylist){
					oVoip.CallBack_Key(data.keylist);
				}
			}
			oVoip.getLongWaterLine();
		});
	};
	//接收消息
	oVoip.getMsgList = function(){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"recvMsg");
		var aLimit = 9876;
		if(oVoip.Waterline>0){
			aLimit = 5;
		}
		getJsonP(url,{waterLine:oVoip.Waterline,client:1,limit:aLimit},function(data) {
			if(data.code==0&&data.msgs!=null&&data.msgs.length>0){
				oVoip.HandleMsg(data.msgs);
			}
		});		
	};
	oVoip.HandleMsg = function(msg){
		for (var i = 0; i < msg.length; i++) {
			var obj = msg[i];
			if (oVoip.Waterline<obj.waterLine) {
				oVoip.doHandUpMsg(obj);
			}			
		}
	}
	oVoip.doHandUpMsg = function(obj){
		oVoip.Waterline = obj.waterLine;
        if (true) {	
			var status = 0;
			var cdrId = 0;
			try{
				context = eval('(' + obj.content + ')');
				status = context.status;							
				cdrId = context.cdrId;
				try{
					var nn = parseInt(context.status);
					status = nn;
				}catch(ee){
					
				}
			}catch(err){
				//return;
			}
			//if(obj.phone!=null&&obj.phone.length==3){
			//	obj.phone = oVoip.extension+obj.phone;
			//}
			if(obj.kind==1||obj.kind==2){
				if(oVoip.phone!=obj.phone&&status==0){
					oVoip.CallBack_Call(obj.kind,obj.phone);
					oVoip.phone = obj.phone;
					oVoip.kind = obj.kind;
					oVoip.status = 0;
				}else if(oVoip.status<status){
					oVoip.status = status;
					switch (status) {
					case (0):
						oVoip.CallBack_Call(obj.kind,obj.phone);
						oVoip.phone = obj.phone;
						oVoip.kind = obj.kind;
						break;
					case (1):
						oVoip.CallBack_Answer(obj.kind,oVoip.phone);
					    break;
					case (2):
						oVoip.getHandUpMsg(obj.phone,oVoip.kind,cdrId);
						oVoip.status = -1;
						break;									
					}	
				}				
			}else if(obj.kind==10&&obj.client==0){
				oVoip.Service_Call(obj.phone);
			}else if(obj.kind>2&&oVoip.ShowMsg!=null){
				oVoip.ShowMsg(obj);
			}
        }
	}
	oVoip.getHandUpMsg = function(phone,kind,aCdrId){
		if(aCdrId==-1){
			var obj = new Object;
			obj.cdrId = aCdrId;
			obj.cdrPeer=kind;
			oVoip.CallBack_HangUp(kind,phone,obj);	
		}else{
			var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"findDialrecord");
			if(phone!=null&&phone.length<5){
				phone = oVoip.extension+phone;
			}
			getJsonP(url,{phoneNum:phone,limit:1,extension:oVoip.userName,scdrId:aCdrId},function(data) {
				if(data.code==0&&data.rows!=null&&data.rows.length>0){
					var obj = data.rows[0];
					oVoip.CallBack_HangUp(kind,phone,obj);
				}else{
					var obj = new Object;
					obj.cdrId = aCdrId;
					obj.cdrPeer=kind;
					oVoip.CallBack_HangUp(kind,phone,obj);
				}
			});
		}
				
	};
	oVoip.answerPhone = function(phone,func){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"sendMsg");  
		getJsonP(url,{phone:phone,kind:6,client:1,lostTime:10},function(data) {
			func(data);		
		});
	}
	oVoip.StopPhone = function(phone,func){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"sendMsg");  
		getJsonP(url,{phone:phone,kind:7,client:1,lostTime:10},function(data) {
			func(data);		
		});
	}
	
	oVoip.getChannelList = function(func){
		var url = oVoip.getUrl(oVoip.userName,oVoip.userPass,"getChannelList");  
		getJsonP(url,{queueSize:1},function(data) {
			func(data);		
		});
	}
	
	oVoip.getUrl = function(user,pass,funcname){
	    console.log(pass)
		var url=oVoip.serviceUrl+'voip/api/jsonpdata.jsonp?callback=?&method='+funcname+'&sa_user='+user+'&sa_password='+$.md5(pass)+"&loginType=jsonpLogin";
		
		console.log(oVoip.serviceUrl)
		console.log(url)
		return url;
	}
	oVoip.timeoutevent = function(){
		var aTime = getNowTimes();
		if(oVoip.exteId != 0&&aTime-oVoip.lastWatertime>1000*35){
			if(window.location.protocol=='https:'){
				if(oVoip.tcpWssPort==0){
					oVoip.getLongWaterLine();
				}
			}else if(oVoip.tcpWsPort==0){
				oVoip.getLongWaterLine();
			}
		}
	}
	setInterval(oVoip.timeoutevent, 1000);
	
	return oVoip;
}
function getNowTimes(){
	var mydate = new Date();
	return mydate.getTime();
}
function getJsonP(url,parms,callback){
	/*var rands = generateMixed(12);
	$.ajax({
		type: 'get',
		async: false,
		url: url,
		data:parms,
		dataType: 'jsonp',
		jsonp: 'clientCallback'+rands,
		jsonpCallback:"clientCallback"+rands,
		success: function(data){
			callback(data);
		},
		error:function(jqXHR, textStatus, errorThrown){
			callback({});
		},
		complete : function(XMLHttpRequest,status){ //请求完成后最终执行参数
　　　　	if(status=='timeout'){//超时,status还有success,error等值的情况 timeout : 40000,
 　　　　	　 callback({});
　　　　	}
　　	}
	});*/

	$.getJSON(url,parms, function(data) {
		callback(data);		
	});
}	

var chars = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
function generateMixed(n) {
    var res = "";
    for(var i = 0; i < n; i++) {
        var id = Math.ceil(Math.random() * 35);
        res += chars[id];
    }
    return res;
}

//-本地有客户端拔号
function callPhone(phone){
	$.ajax({
		type: 'get',
		async: false,
		url: 'http://127.0.0.1:10800/?type=3&phone=' + phone,
		dataType: 'jsonp',
		jsonp: 'clientCallback',
		jsonpCallback:"clientCallback",
		success: function(data){
			if(!data.code && data.code != 0){
				$.messager.alert('提示','呼叫失败，客户端呼叫错误','error');
			}
		},
		error: function(data){
			if(!data.code && data.code != 0){
				$.messager.alert('提示','呼叫失败，无法连接客户端','error');
			}
		}
	});
}

function GetRandomNum(Min, Max) {
    var Range = Max - Min;
    var Rand = Math.random();
    return(Min + Math.round(Rand * Range));
}
function initVoipCall(data){
	data=data||{};
	voip_call=new voipCall();
	voip_call.init("/");
	voip_call.CallBack_login=function(code,data){// 提示登录出错
		if(code!=0) layer.alert(data);
//		layer.msg('登录成功');
	};
	voip_call.ShowMsg = function(obj){// 消息通知
//		layer.msg('消息通知<br/>'+JSON.stringify(obj));
	};
	voip_call.CallBack_Call = function(peer,phone){
		voip_call.connect_phone=true;
		if(data.webCallOpen!=1){
			openUrl(peer==2?'来电弹屏':'呼出弹屏',"/voip/ai/customer/custinfo.html?phone="+phone,"80%","100%");
		}
	};
	voip_call.userlogin($('.i-loginId').val(),$('.i-pwd').val());
	var a,out;
	$('.moreOpts').append(a=$('<dd><a href="javascript:;">签入</a></dd>'));
	$('.moreOpts').append(out=$('<dd><a href="javascript:;">签出</a></dd>'));
	a.click(function(){
		voip_call.setUserCheckInOut(0,function(data){
			layer.msg(data.code==0?'签入成功':'签入失败');
		});
	});
	out.click(function(){
		voip_call.setUserCheckInOut(1,function(data){
			layer.msg(data.code==0?'签出成功':'签出失败');
		});
	});
}